<template>
  <div class="edit-container">
    <van-nav-bar title="编辑资料" left-arrow @click-left="$router.back()" />
    <van-cell-group>
      <van-cell title="头像" is-link center>
        <label for="photo">
          <img :src="imgSrc" alt="选择头像" @click="changePhoto" />
          <input type="file" style="display: none" ref="photoFile" id="photo" @change="imgChoose" />
        </label>
      </van-cell>
      <van-cell title="名称" is-link center>
        <template #default>
          <span @click="show = true">{{ theName }}</span>
        </template>
      </van-cell>
      <van-cell title="性别" is-link center>
        <template #default>
          <!-- 这里不要用===，不然数据类型对不上 -->
          <span @click="sexShow = true">{{ theSex == 0 ? '男' : '女' }}</span>
        </template>
      </van-cell>
      <van-cell title="生日" is-link center>
        <template #default>
          <span @click="showDate = true">{{ theBirthday }}</span>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 修改姓名弹出框 -->
    <van-dialog
      v-model="show"
      v-focus
      title="修改名称"
      show-cancel-button
      getContainer="body"
      :before-close="beforeCloseFn"
    >
      <input type="text" v-model.trim="userName" />
    </van-dialog>
    <!-- 修改性别弹出框 -->
    <van-dialog
      v-model="sexShow"
      title="修改性别"
      show-cancel-button
      getContainer="body"
      :before-close="beforeCloseSexFn"
    >
      <form>
        <input
          type="radio"
          name="sex"
          value="0"
          :checked="sex === 0 ? true : false"
          v-model="sex"
          style="width: 0.3467rem; height: 0.3467rem"
          id="boy"
        />
        <label for="boy">男</label>
        <input
          type="radio"
          name="sex"
          value="1"
          :checked="sex === 1 ? true : false"
          v-model="sex"
          style="width: 0.3467rem; height: 0.3467rem"
          id="girl"
        />
        <label for="girl">女</label>
      </form>
    </van-dialog>
    <!-- 日历选择器 -->
    <van-popup
      v-model="showDate"
      round
      position="bottom"
      :style="{ height: '30%' }"
      get-container="body"
    >
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="confirmDateFn"
        @cancel="showDate = false"
      />
    </van-popup>
  </div>
</template>

<script>
import { getUserProfileAPI, UserPhotoAPI, upDataUserProfileAPI } from '@/api'
import dayjs from 'dayjs'
import { Notify } from 'vant'
import { mapMutations } from 'vuex'
export default {
  name: 'Edit',
  data() {
    return {
      userProfile: {},
      imgSrc: '', // 图片地址
      show: false, // 修改姓名弹出框显示与否
      userName: '', // 用户名
      theName: '',
      sexShow: false, // 显示性别弹框
      sex: '', // 性别
      theSex: '',
      showDate: false, // r日历弹窗
      minDate: new Date(1960, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(),
      theBirthday: '' // 出生日期
    }
  },
  async created() {
    const {
      data: { data }
    } = await getUserProfileAPI()
    // console.log(data)
    this.imgSrc = data.photo
    this.userName = data.name
    this.theName = data.name
    this.sex = data.gender
    this.theSex = data.gender
    this.theBirthday = data.birthday
  },
  methods: {
    ...mapMutations(['changeNewPhoto']),
    // 点击头像
    changePhoto() {
      console.log('点击头像')
      // 方法2：通过click()方法来触发表单
      // this.$refs.photoFile.click()
    },
    // 头像改变
    async imgChoose(e) {
      console.log('头像改变')
      // 防止用户点击取消后，头像显示错误问题
      if (e.target.files.length === 0) return
      // 方法2：本地更换头像（不走网络，显示时间快）
      const url = e.target.files[0]
      console.log(url)
      if ('FileReader' in window) {
        const img = new FileReader()
        img.readAsDataURL(url)
        img.onload = ({ target }) => {
          this.imgSrc = target.result
        }
      }
      // 发送请求，更新头像
      // 如果你的请求体直接是FormData表单对象，你也不用自己添加
      // Content-Type,axios发现数据请求体是表单对象，它也不会转换成json字符串
      // 也不会带Content-Type: application/json，而是交给浏览器，浏览器发现请求体是formData会自己携带Content-Type
      // Content-Type: application/json; axios携带的，前提:data请求体是对象->json字符串->发给后台
      // Content-Type: multipart/form-data;浏览器携带的，前提: data请求体必须FormData类型对象
      const theImg = new FormData()
      theImg.append('photo', url)
      const {
        data: { data }
      } = await UserPhotoAPI(theImg)
      console.log(data)
      //  方法1：通过后台返回的头像地址来保存头像(要通过网络，太慢)
      // this.imgSrc = data.photo
      this.changeNewPhoto(data.photo)
    },
    // 关闭前的回调函数(修改名称)
    async beforeCloseFn(action, done) {
      // 点击了确认按钮
      if (action === 'confirm') {
        // 正则表达式：数字，字母，汉字组成，1到7位
        const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]{1,8}$/
        if (reg.test(this.userName)) {
          // 显示更改的名称
          this.theName = this.userName
          const data = await upDataUserProfileAPI({ name: this.userName })
          console.log(data)
          done()
        } else {
          Notify({ type: 'warning', message: '名称由数字,字母和汉字组成,1到7位', duration: 1000 })
          done(false)
        }
        // 点击取消按钮关闭弹窗
      } else {
        done()
      }
    },
    // 关闭前的回调函数(修改性别)
    async beforeCloseSexFn(action, done) {
      // 点击了确认按钮
      if (action === 'confirm') {
        this.theSex = this.sex
        const data = await upDataUserProfileAPI({ gender: this.sex })
        console.log(data)
        done()
        // 点击取消按钮关闭弹窗
      } else {
        done()
      }
    },
    // 日期选择器确认按钮
    async confirmDateFn() {
      this.theBirthday = dayjs(this.currentDate).format('YYYY-MM-DD')
      const data = await upDataUserProfileAPI({ birthday: this.theBirthday })
      console.log(data)
      this.showDate = false
    }
  }
}
</script>

<style lang="less" scoped>
.edit-container {
  .van-cell-group {
    .van-cell {
      img {
        width: 50px;
        height: 50px;
        border-radius: 50%;
      }
    }
  }
}
.van-dialog {
  text-align: center;
  input {
    text-align: center;
    outline: none;
    border: 0;
  }
}
.van-popup {
  // 强制修改样式
  height: 50% !important;
}
</style>
